package com.example.jk.middlewares;

import java.util.ArrayList;
import java.util.List;

import com.example.jk.core.Context;
import com.example.jk.core.Middleware;
import com.example.jk.core.Next;

public class RouteMiddleware implements Middleware {

	public List<Route> routes = new ArrayList<>();


	public void register(String path, String method, Next handler) {
		boolean foundRoute = false;
		for (Route route : routes) {
			if (route.path.equals(path)) {
				route.handlers.put(method, handler);
				foundRoute = true;
				break;
			}
		}
		if (!foundRoute) {
			Route newRoute = new Route(path);
			newRoute.handlers.put(method, handler);
			routes.add(newRoute);
		}
	}

	@Override
	public void handle(Context context, Next next) {
		Route route = getRoute(context.requestPath, context.method);
		if (route != null) {
			Next handler = route.handlers.get(context.method);
			if (handler != null) {
				handler.handle(context);
				
				
			}
		}
		
		next.handle(context);//继续执行下一个中间件
	}

	public Route getRoute(String requestPath, String method) {
		for (Route route : routes) {
			if (requestPath.equalsIgnoreCase(route.path)) {
				Object handler = route.handlers.get(method);
				if (handler != null) {
					return route;
				}
			}
		}
		return null;
	}
}